<?php

namespace App\Http\Controllers\Report;

use App\Exports\ReportRegionKeyProductExport;
use App\Http\Conf\ResultInfo;
use App\Http\Controllers\Controller;
use App\Http\Models\Business\CacheInvoiceRegionKeyProduct;
use App\Http\Models\Report\ReportRegionKeyProduct;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class RegionKeyProductProgress extends Controller
{
    public function index(Request $request)
    {
        $year = is_numeric($request->year) ? $request->year : date('Y', time());
        $report_region_key_product = new ReportRegionKeyProduct($year);

        return view('report.region_key_product_progress.index', [
            'year' => $year,
            'report_region_key_product' => $report_region_key_product,
        ]);
    }


    public function cache(Request $request)
    {
        $year = $request->year;
        //先删除已经缓存的数据
        CacheInvoiceRegionKeyProduct::where(['year' => $year])->delete();

        //再添加数据
        $invoice_infos = DB::table('invoice_details_sd002')
            ->leftJoin('material', 'invoice_details_sd002.material', '=', 'material.material')
            ->select(['invoice_details_sd002.sales_region_code', 'material.category_key_product_id', DB::raw('sum(quantity) as quantity')])
            ->where([
                'invoice_details_sd002.year' => $year,
                'material.year' => $year,
                'invoice_details_sd002.distribution_channel_code' => 'Z1',
                ['material.category_key_product_id', '<>', 0],
            ])->groupBy('invoice_details_sd002.sales_region_code', 'material.category_key_product_id')
            ->get()->toArray();

        foreach ($invoice_infos as $invoice_info) {
            $model = new CacheInvoiceRegionKeyProduct();
            $model->year = $year;
            $model->sales_region_code = $invoice_info->sales_region_code;
            $model->category_key_product_id  = $invoice_info->category_key_product_id;
            $model->quantity = $invoice_info->quantity;
            $model->save();
        }

        return ['status' => ResultInfo::SUCCESS];
    }

    public function export()
    {
        Excel::store(new ReportRegionKeyProductExport, '/export/大区零售目标进度_' . date('Ymd_His', time()) . '.xlsx');
        return ['status' => ResultInfo::SUCCESS];
    }
}
